package util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author liudongs
 * @Date 2020/11/6 11:26
 * @Version 1.0
 * @E-mail liudongs@aliyun.com
 * md5加密工具类
 */
public class MD5Utils {

    public static String md5(String value){
        String result = null;
        MessageDigest md5 = null;
        try{
            md5 = MessageDigest.getInstance("MD5");
            md5.update((value).getBytes("UTF-8"));
        }catch (NoSuchAlgorithmException error){
            error.printStackTrace();
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        assert md5 != null;
        byte b[] = md5.digest();
        int i;
        StringBuffer buf = new StringBuffer("");

        for(int offset=0; offset<b.length; offset++){
            i = b[offset];
            if(i<0){
                i+=256;
            }
            if(i<16){
                buf.append("0");
            }
            buf.append(Integer.toHexString(i));
        }

        result = buf.toString().toUpperCase();
        return result;
    }

    /**
     * 盐值生成
     * @return
     */
    public final static String saltUtils(){

        /**
         *  如果字符种类不够，可以自己再添加一些
         */
        String range = "0123456789abcdefghijklmnopqrstuvwxyz";
        ThreadLocalRandom random = ThreadLocalRandom.current();

        StringBuilder result = new StringBuilder();
        result.append(System.currentTimeMillis());

        /**
         * 要生成几位，就把这里的数字改成几 目前业务要求三位随机码
         */
        for (int i = 0; i < 8; i++) {
            result.append(range.charAt(random.nextInt(range.length())));
        }

        return result.toString();
    }

    public static void main(String[] args) {
//        System.err.println(MD5Utils.md5("123456"));
//        System.err.println("E10ADC3949BA59ABBE56E057F20F883E".equals(MD5Utils.md5("123456")));
        System.out.println(MD5Utils.md5("18231157516"));
        System.out.println("67A92C168A843B97C8D6008651343ED9".equals(MD5Utils.md5("18231157516")));

        System.out.println(MD5Utils.saltUtils());
    }
}
